import javafx.util.Pair;

import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-09-20
 * Time: 23:07
 */
class Solution6 {
    public int[] topKFrequent(int[] nums, int k) {
        // 1.统计频率
        Map<Integer,Integer> hash = new HashMap<>();

        for(int x : nums) {
            hash.put(x,hash.getOrDefault(x,0)+1);
        }

        // 2.建立小根堆
        PriorityQueue<Pair<Integer,Integer>> heap = new PriorityQueue<>((a, b)->{
            return a.getValue()-b.getValue();
        });

        for(Map.Entry<Integer,Integer> e : hash.entrySet()) {
            heap.offer(new Pair<Integer,Integer>(e.getKey(),e.getValue()));
            if(heap.size() > k) {
                heap.poll();
            }
        }

        int[] ret = new int[k];
        int i = k-1;
        while(!heap.isEmpty()) {
            ret[i] = heap.poll().getKey();
            i--;
            if(i < 0) {
                break;
            }
        }
        return ret;
    }
}
